package com.aube.plugin.figure;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.origin.DataConvertUtil;
import com.aube.plugin.origin.HomeCategoryModel;
import com.aube.plugin.origin.ModuleLauncher;
import com.aube.plugin.origin.R;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.dynamicload.DLBridge;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.PluginPackageManager;
import com.huyn.baseframework.dynamicload.PositionManageUtil;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.Character;
import com.huyn.baseframework.model.ThemeModel;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.statesync.ActorStateAsyncHelper;
import com.huyn.baseframework.statesync.INetworkRequestBridge;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;
import com.ryg.dynamicload.DLBasePluginFragmentActivity;

import java.util.HashMap;

/**
 * Created by huyaonan on 16/5/24.
 */
public class CharacterActivity extends DLBasePluginFragmentActivity {

    public static final String TEMPLATE_ACTOR = "actor";
    public static final String HEADER_ACTOR = "actorHead";
    public static final String ACTOR = "ACTOR";

    private LinearLayout mLinear, mLinear2;
    private ScrollView mScrollview;
    private ImageView mImg, mAvatar;
    private View mBg;
    private int mLastScrollY = 0;

    private BlurViewDecorator mBlurview;
    private BlurViewDecorator mBlurviewTop;
    private int targetHeight;
    private ParallaxTopBarLayout mTopBar;
    private View mBlurTop;

    private int statusHeight = 0;
    private int topbarheight = 200;
    private Character mCharactor;
    private PluginPackageManager mPluginManager;

    private View mHeadLayout;
    private ImageView mHeadPlaceHolder, mHeadImg;

    private ActorStateAsyncHelper mStateHelper;

    private View mRoot;
    private FrameLayout mBlurLayout;
    private int mMaskTranslationY = 0;

    private PositionManageUtil mPositionManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_character);

        mRoot = findViewById(R.id.character_root);

        mCharactor = (Character) getIntent().getSerializableExtra(ACTOR);

        if(mCharactor == null) {
            finish();
            return;
        }

        if(StringUtils.isNotBlank(mCharactor.actorName))
            UmengUtils.reportUmengEvent(that, UmengUtils.TO_CHARACTER, mCharactor.actorName);

        statusHeight = SysUtil.getStatusHeight(that);
        topbarheight = getResources().getDimensionPixelOffset(R.dimen.actionbar_height);

        mBlurTop = findViewById(R.id.blurring_top);

        mLinear = (LinearLayout) findViewById(R.id.linearlayout);
        mLinear2 = (LinearLayout) findViewById(R.id.linearlayout2);
        mScrollview = (ScrollView) findViewById(R.id.scrollview);
        mImg = (ImageView) findViewById(R.id.cover);
        mAvatar = (ImageView) findViewById(R.id.avatar);
        mBg = findViewById(R.id.bg_layout);

        //头像部分
        mHeadLayout = findViewById(R.id.avatar_header_layout);
        mHeadPlaceHolder = (ImageView) findViewById(R.id.avatar_header);
        mHeadImg = (ImageView) findViewById(R.id.avatar_header_real);

        mBlurLayout = (FrameLayout) findViewById(R.id.blur_container);
        try {
            mBlurview = getBlurView(false);
            mBlurview.setBlurredView(mBg);
            mBlurview.setOverlayColor(getResources().getColor(R.color.blur_color));

            mBlurviewTop = getBlurView(false);
            mBlurviewTop.setBlurredView(mBg);
            mBlurviewTop.setOverlayColor(getResources().getColor(R.color.blur_color));
            mBlurviewTop.setAlpha(0f);

            mBlurLayout.addView(mBlurviewTop, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mBlurLayout.addView(mBlurview, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mTopBar = (ParallaxTopBarLayout) findViewById(R.id.topbar);

        mPositionManager = new PositionManageUtil(mScrollview);

        setImgWithRes(mImg, R.drawable.bk_default);
        setImgWithRes(mAvatar, R.drawable.bk_default);
        setImgWithRes(mHeadPlaceHolder, R.drawable.bk_default);
        setImgWithRes(mHeadImg, R.drawable.bk_default);
        setBgWithRes(mBlurTop, R.drawable.gradient_blur_top);

        mScrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int y = mScrollview.getScrollY();
                if (y == mLastScrollY)
                    return;
                mLastScrollY = y;
                if (y >= targetHeight - topbarheight - statusHeight) {
                    mTopBar.updateTitleOffset(targetHeight - topbarheight - statusHeight);
                } else {
                    mTopBar.updateTitleOffset(y);
                }

                int targetY = targetHeight - y;
                mBlurview.setTranslationY(targetY < 0 ? 0 : targetY);
                mBlurview.invalidate();

                mBlurviewTop.setTranslationY(-y);
                float alpha = 0;
                if (y > targetHeight - topbarheight - statusHeight) {
                    alpha = 1f;
                } else {
                    alpha = y * 1f / (targetHeight - topbarheight - statusHeight);
                }
                mBlurviewTop.setAlpha(alpha);
                mBlurviewTop.invalidate();

                mBlurTop.setTranslationY((targetY < 0 ? -targetHeight : -y) + mMaskTranslationY);
                mBlurTop.setAlpha(1 - alpha);

                if(mPositionManager != null)
                    mPositionManager.listener(y);
            }
        });

        int width = SysUtil.getAbsoluteScreenWidth(that);
        targetHeight = width + statusHeight;

        View header = new View(that);
        mLinear.addView(header, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, targetHeight-topbarheight-statusHeight));

        mScrollview.setPadding(0, topbarheight+statusHeight, 0, 0);

        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) mTopBar.getLayoutParams();
        params2.height = targetHeight;
        mTopBar.setTopbarHeight(topbarheight);
        mTopBar.updateContent(DataConvertUtil.toSimpleCharacter(mCharactor), null, mRoot, getBridge());

        mBlurview.setTranslationY(targetHeight);

        RelativeLayout.LayoutParams topParams = (RelativeLayout.LayoutParams) mBlurTop.getLayoutParams();
        topParams.height = targetHeight/3;
        mMaskTranslationY = targetHeight-targetHeight/3;
        mBlurTop.setTranslationY(mMaskTranslationY);

        FrameLayout.LayoutParams params3 = (FrameLayout.LayoutParams) mBlurviewTop.getLayoutParams();
        params3.height = targetHeight;

        FrameLayout.LayoutParams headParams = (FrameLayout.LayoutParams) mHeadLayout.getLayoutParams();
        headParams.height = targetHeight;

        mPluginManager = PluginPackageManager.getInstance();
        mStateHelper = ActorStateAsyncHelper.getInstance(that, new INetworkRequestBridge() {
            @Override
            public void executeRequest(HashMap<String, String> params, Class modelClass, String TAG, Response.Listener listener) {
                exeHttpRequest(params, modelClass, TAG, listener);
            }
        });

        getData();
    }

    public void getData() {
        HashMap<String, String> maps = new HashMap<>();
        maps.put("templateCode", TEMPLATE_ACTOR);
        maps.put("relatedId", mCharactor.relatedId);
        maps.put(OpenApi.API_METHOD, OpenApi.HOME_DETAIL);
        BFJSONRequest request = new BFJSONRequest(HomeCategoryModel.class, maps, new Response.Listener<HomeCategoryModel>() {
            @Override
            public void onResponse(HomeCategoryModel response) {
                Utils.sysout("***************1");
                if(response != null && response.success()) {
                    setupModules(response);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }

            @Override
            public void onStart() {

            }
        });
        HttpRequestLoader.getInstance(that).startHttpLoader(request);
    }

    private int getThemeColor() {
        ThemeModel theme = mPluginManager.getTheme();
        if(theme == null)
            return 0;
        return theme.getThemeColor();
    }

    private void setupModules(HomeCategoryModel model) {
        Utils.sysout("***************2");
        if(mPluginManager == null)
            return;
        Utils.sysout("***************3");
        int color = getThemeColor();
        if(color == 0)
            color = getResources().getColor(R.color.theme);
        if(model != null && model.success() && model.size() > 0) {
            mLinear2.removeAllViews();
            int index = 0;
            int size = model.data.size();
            for(Category cate : model.data) {
                Utils.sysout("***************4/" + cate.modelCode);
                if(ModuleLauncher.isInThisPackage(cate.modelCode)) {
                    Utils.sysout("***************5");
                    cate.templateType = TEMPLATE_ACTOR;
                    cate.relatedId = mCharactor.relatedId;
                    try {
                        DLLayout view = DynamicLoaderHelper.loadTargetLayout(that, mPluginPackage, ModuleLauncher.getClassName(cate.modelCode));

                        if (view != null) {
                            Utils.sysout("***************7:" + view.getClass().getName());
                            mLinear2.addView(view);
                            if (mPositionManager != null)
                                view.registToManager(mPositionManager);
                            view.setDLBridge(getBridge());
                            view.fillData(cate);

                            if (color != 0)
                                view.setTheme(color);

                            if (index != size - 1)
                                addDivider();
                        } else {
                            index--;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        index--;
                    }
                } else  if(mPluginManager.hasModule(cate.modelCode) && cate.size() > 0) {
                    Utils.sysout("***************6");
                    cate.templateType = TEMPLATE_ACTOR;
                    cate.relatedId = mCharactor.relatedId;
                    try {
//                        DLLayout view = mPluginManager.inflatePluginLayout(that, cate.modelCode, cate.launchclass, true);
                        DLLayout view = mPluginManager.inflatePluginLayout(that, cate.modelCode, ModuleLauncher.getLaunchClass(cate.modelCode), true);

                        if(view != null) {
                            Utils.sysout("***************8");
                            mLinear2.addView(view);
                            if(mPositionManager != null)
                                view.registToManager(mPositionManager);
                            view.setDLBridge(getBridge());
                            view.fillData(cate);

                            if (color != 0)
                                view.setTheme(color);

                            if (index != size - 1)
                                addDivider();
                        } else {
                            index--;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        index--;
                    }
                } else if(HEADER_ACTOR.equalsIgnoreCase(cate.modelCode)) {
                    setupActorHeader(DataConvertUtil.parseActorHeader(cate.dataDetail));
                }
                index++;
            }
        }

        if(mPositionManager != null) {
            mPositionManager.reportItemsPosition();
            mPositionManager.storeListenerPositions(500);
        }
    }

    private DLBridge getBridge() {
        return (DLBridge) that;
    }

    private void addDivider() {
        View view = new View(that);
        view.setBackgroundResource(R.color.divider_color);
        int space = getResources().getDimensionPixelOffset(R.dimen.widget_margin);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1);
        params.leftMargin = space;
        params.rightMargin = space;
        mLinear2.addView(view, params);
    }

    public void setupActorHeader(final DataConvertUtil.SimpleCharacter simpleIndexHeader) {
        if(simpleIndexHeader == null)
            return;

        mTopBar.updateContent(simpleIndexHeader, mStateHelper, mRoot, getBridge());
        ImageLoader.getInstance(that).preloadBitmap(simpleIndexHeader.picurl, new ImageLoader.IPreloadCallback<Bitmap>() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                mAvatar.setImageBitmap(bitmap);
                mHeadImg.setImageBitmap(bitmap);
                final ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
                anim.setDuration(500);
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        float alpha = (float) animation.getAnimatedValue();
                        mImg.setAlpha(alpha);
                        mHeadPlaceHolder.setAlpha(alpha);
                        mBlurview.invalidateSelf();
                        mBlurviewTop.invalidateSelf();
                    }
                });
                anim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mImg.setVisibility(View.GONE);
                        mHeadPlaceHolder.setVisibility(View.GONE);
                    }
                });
                anim.start();
            }

            @Override
            public void onFail() {

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mTopBar != null)
            mTopBar.onDestroy();
    }

    @Override
    public View getRootView() {
        return mRoot;
    }
}
